/**
 * @filename:SysAdminServiceImpl 2022年1月27日
 * @project Wonder wallet Framework  V1.0
 * Copyright(c) 2018 LuZhongren Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.admin.service.impl;

import com.wonder.admin.domain.SysAdmin;
import com.wonder.admin.domain.vo.LoginBody;
import com.wonder.admin.mapper.SysAdminDao;
import com.wonder.admin.service.SysAdminService;
import com.wonder.common.config.WonderConfig;
import com.wonder.common.constants.Constants;
import com.wonder.common.exception.TokenException;
import com.wonder.common.exception.XhadminException;
import com.wonder.common.exception.user.CaptchaException;
import com.wonder.common.exception.user.CaptchaExpireException;
import com.wonder.common.exception.user.UserPasswordNotMatchException;
import com.wonder.framework.authorization.TokenAdminManager;
import com.wonder.framework.authorization.TokenAdminModel;
import com.wonder.framework.manager.AsyncManager;
import com.wonder.framework.manager.factory.AsyncFactory;
import com.wonder.framework.redis.RedisCache;
import com.wonder.admin.request.SysAdminRequest;
import com.wonder.common.utils.GoogleAuthenticator;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.utils.StringUtils;
import com.wonder.common.utils.sign.Md5Utils;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;



/**   
 * @Description:TODO(后台用户管理服务实现)
 *
 * @version: V1.0
 * @author: LuZhongren
 * 
 */
@Service
public class SysAdminServiceImpl  extends ServiceImpl<SysAdminDao, SysAdmin> implements SysAdminService  {

	
	 private String omitCaptcha="12345678WonderSoftwareEngineering";
	 
	 @Autowired
	 private RedisCache redisCache;
	 
	 @Autowired
	 private TokenAdminManager tokenManager;
	 
   /**
     * 修改后台用户管理信息
     * 
     * @param SysAdmin信息
     * @return 结果
     */
    @Override
    public int updateEx(SysAdmin sysAdmin){
       if(sysAdmin!=null)
		     return this.baseMapper.updateById(sysAdmin);
       return 0;
    }
    
    
//    /**
//	 * Description:后台用户管理分页返回
//	 * @request:检索条件
//	 * @page：分页参数
//	 * @return:分页记录
//	 */
//	@Override 
//	public IPage<SysAdmin> selectList(SysAdminRequest request, Page<SysAdmin> page){
//	    QueryWrapper<SysAdmin> lambdaQueryWrapper = new QueryWrapper<>();
//	             
//        if (StringUtils.isNotEmpty(request.getName())) {
//			lambdaQueryWrapper.eq("name", request.getName());
//		} 
//        if (StringUtils.isNotEmpty(request.getUser())) {
//			lambdaQueryWrapper.eq("user", request.getUser());
//		}   
//	    if (null != request.getType()) {
//	       lambdaQueryWrapper.eq("type", request.getType());
//	      }               
//	    if (null != request.getStatus()) {
//	       lambdaQueryWrapper.eq("status", request.getStatus());
//	      }   
//	    if (null != request.getRole_id()) {
//		       lambdaQueryWrapper.eq("a.role_id", request.getRole_id());
//		      }  
//	      
//		lambdaQueryWrapper.orderByDesc("a.user_id");	
//		IPage<SysAdmin> selectPage = this.baseMapper.selectAdminList(page, lambdaQueryWrapper);
//
//		return selectPage;
//    }
	
	/**
	 * 后台用户管理分页返回
	 * 分页列表
	 */
	@Override
	public List<SysAdmin> selectList(SysAdminRequest user,Page<SysAdmin> page) {
		// TODO Auto-generated method stub
		return this.baseMapper.selectAdminList(page, user);
	}
	
	@Override
	public String login(LoginBody loginBody) throws Exception {
		String user=loginBody.getUsername();
//		String uuid=loginBody.getKey();
		String pwd=loginBody.getPassword();
		String googleSecret=loginBody.getGoogleSecret();
//		String code=loginBody.getVerify();
//
//		if(!omitCaptcha.equals(loginBody.getVerify())) {
//	        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
//	        String captcha = (String)redisCache.get(verifyKey);
//	        redisCache.delete(verifyKey);
//	        if (captcha == null)
//	        {
//	            AsyncManager.me().execute(AsyncFactory.recordLogininfor(user, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
//	            throw new CaptchaExpireException();
//	        }
//	        if (!code.equalsIgnoreCase(captcha))
//	        {
//	            AsyncManager.me().execute(AsyncFactory.recordLogininfor(user, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
//	            throw new CaptchaException();
//	        }
//    	}
		
		 // 执行登录
        LambdaQueryWrapper<SysAdmin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysAdmin::getUser, user);
        lambdaQueryWrapper.eq(SysAdmin::getPwd, Md5Utils.hash(pwd));
        SysAdmin sysAdmin = this.getOne(lambdaQueryWrapper);
        if(null == sysAdmin){
        	 AsyncManager.me().execute(AsyncFactory.recordLogininfor(user, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
 
        if(sysAdmin.getStatus()==0){
        	AsyncManager.me().execute(AsyncFactory.recordLogininfor(user, Constants.LOGIN_FAIL, MessageUtils.message("user.blocked")));
            throw new XhadminException("user.blocked");
        }
        //Here can add the google secret check......
        if(WonderConfig.isGoogleAuth()) {
        	String googleKey=sysAdmin.getGoogle_secret();
        	if(!StringUtils.hasText(googleSecret) || !StringUtils.isNumeric(googleSecret))
        		   throw new XhadminException("google.auth.fail");
        	boolean googleAuth=GoogleAuthenticator.authcode(googleSecret, googleKey);
        	if(!googleAuth) throw new XhadminException("google.auth.fail");
        	
        }
        
        //Save the login info to database
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(user, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        
        TokenAdminModel tokenModel = tokenManager.createToken(user, sysAdmin.getUser_id().toString(), TokenAdminModel.TOKEN_REDIS);
        //Create token and save the token to Redis and return the token to user
        
		return tokenModel.getToken();
	}
	

	@Override
    public Boolean logout(String token) throws Exception {
        tokenManager.deleteToken(token, TokenAdminModel.TOKEN_REDIS);
        return true;
    }
	
	@Override
	public SysAdmin getAdminByToken(String token) throws Exception{
	        Boolean tokenExsit = tokenManager.checkToken(token, TokenAdminModel.TOKEN_REDIS);
	        if(!tokenExsit){
	            throw new TokenException("user.token.not.effect");
	        }
	        Long user_id = tokenManager.getToken(token, TokenAdminModel.TOKEN_REDIS);
	        SysAdmin sysAdmin=this.getById(user_id);
	        
	        return sysAdmin;
	        
	    }
    
	
}